/*
 * Copyright (c) 2017 Baidu, Inc. All Rights Reserve.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yinhai.uid.worker;

import com.yinhai.uid.utils.NetUtils;
import com.yinhai.uid.worker.entity.WorkerNodeModel;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ValueOperations;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RedisWorkerIdAssigner implements WorkerIdAssigner {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisWorkerIdAssigner.class);

	private static final String WORKER_ID = "workerId";

	private static final String WORKER_NODE = "worker_node";

    private static final String YYYY_MM_DD = "yyyy-MM-dd";

	private static final String YYYY_MM_DD_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";

	@Resource
	private ValueOperations<String, Object> valueOperations;

	@Resource
	private HashOperations<String, String, Object> hashOperations;

    public long assignWorkerId() {
		long workerId = valueOperations.increment(WORKER_ID,1);
		hashOperations.put(WORKER_NODE,WORKER_NODE + ":" + workerId,buildWorkerNode(workerId));
		return workerId;
	}

	private WorkerNodeModel buildWorkerNode(long workerid) {
		WorkerNodeModel workerNodeModel = new WorkerNodeModel();
		workerNodeModel.setId(workerid);
		workerNodeModel.setHostName(NetUtils.getLocalAddress());
		workerNodeModel.setPort(System.currentTimeMillis() + "-" + RandomUtils.nextInt(100000));
		workerNodeModel.setType(2);
		workerNodeModel.setLaunchDate(getStringDate(YYYY_MM_DD));
		String time = getStringDate(YYYY_MM_DD_HH_mm_ss);
		workerNodeModel.setModified(time);
		workerNodeModel.setCreated(time);
		return workerNodeModel;
	}

	private String getStringDate(String format) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(new Date());
	}


}
